package free.mrchen.boot.gate.server.def;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class CustomRouteDefinitionLocator implements RouteDefinitionLocator , InitializingBean {


    private final GateServerRouteProperties gateServerRouteProperties;

    private final RouteDefFeature routeDefFeature;

    public CustomRouteDefinitionLocator(GateServerRouteProperties gateServerRouteProperties, RouteDefFeature routeDefFeature) {
        this.gateServerRouteProperties = gateServerRouteProperties;
        this.routeDefFeature = routeDefFeature;
    }


    @Override
    public Flux<RouteDefinition> getRouteDefinitions() {
        try {
            return Flux.fromStream( loadRouteDefinition().stream() );
        } catch (Exception e) {
            return Flux.error(e);
        }
    }

    protected List<RouteDefinition> loadRouteDefinition() {
        final List<RouteDefinition> routeDefinitions = new ArrayList<>();
        for (Map.Entry<String, RouteDef> entry : routeDefFeature.listStable().entrySet()) {
            routeDefinitions.add( RouteDefConvert.toDefinition( entry.getValue() ));
        }
        return routeDefinitions;
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        routeDefFeature.init();
    }


}
